package com.onetech.adrewards.free.activities;

import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.analytics.tracking.android.EasyTracker;
import com.onetech.adrewards.free.R;
import com.onetech.adrewards.free.config.AppConfig;
import com.onetech.adrewards.free.dialogs.SuccessDialog;
import com.onetech.adrewards.free.models.CommonModel;
import com.onetech.adrewards.free.objects.InvitedFriendDTO;
import com.onetech.adrewards.free.objects.RegisterSuccessDTO;
import com.onetech.adrewards.free.objects.ResultDTO;
import com.onetech.adrewards.free.utils.AdrewadsUtils;
import com.todddavies.components.progressbar.ProgressWheel;

public class LoginInviteCodeSendMailActivity extends BaseActivity {
	private TextView mMessage=null;
	private TextView mInviteCode=null;
	private EditText mEmail=null;
	private List<String> mDomains = null;
	private View mMainView=null;
	
	
	private Spinner mMailDomain = null;

	private TextView mInviteNote=null;
	
	private View mSendMailBtn=null;
	
	private ProgressWheel mProgressBar=null;
	
	private long mCurrentTime = 0;
	private boolean isSending=false;
	
	private View mNotFoundData=null;
	private View mWaitingForLoading=null;
	protected View mBtnRetry=null;
	protected ProgressWheel mProgress=null;
	
	private InvitedFriendDTO mInvitedData=null;
	
	 
	
	private SendMailInviteCodeDataTask mSendMail=null;
	private LoadInvitedDataTask mLoadInvitedDataTask=null;
	
	RegisterSuccessDTO mResult=null;
	
	private int buttonPressId=-1; 
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setMainView(R.layout.activity_login_invite_code_send_mail_layout);
		setAppTittle(getString(R.string.app_name));
		showMyPoints(false);
		initView();
		initListener();
	}
	
	private void initView() {
		mMessage=(TextView)findViewById(R.id.msg);
		mInviteCode=(EditText)findViewById(R.id.inviteCode);
		mInviteNote=(TextView)findViewById(R.id.inviteNote);
		mEmail = (EditText)findViewById(R.id.email);
		mMailDomain =  (Spinner) findViewById(R.id.mailDomain);
		
		 
		
		mSendMailBtn=(LinearLayout)findViewById(R.id.btnSendMail);
		
		
		initNotFoundAndLoadingView();
		mMainView=(LinearLayout)findViewById(R.id.mainContainer);
		//showMainView(false);
		showFooterView(false);
		
		mProgressBar=(ProgressWheel)findViewById(R.id.splashProgressBar);
		mProgressBar.setText("");
		mProgressBar.setContourColor(Color.TRANSPARENT);
		mProgressBar.spin();
		mProgressBar.setVisibility(View.INVISIBLE);
	}
	
	protected void initNotFoundAndLoadingView(){
		mNotFoundData=(LinearLayout) findViewById(R.id.notFoundDataContainer);		
		mWaitingForLoading=(LinearLayout) findViewById(R.id.waitingLoading);
		mProgress=(ProgressWheel)findViewById(R.id.progressWheel);
		mProgress.spin();
		showNotFoundOrLoadingView(false, true);
		mBtnRetry=(LinearLayout)findViewById(R.id.btnRetry);
		
	}
	
	protected void initRetryButtonListener(){
		mBtnRetry.setOnClickListener(this);
	}
	
	private void initListener() {
		mSendMailBtn.setOnClickListener(this);
		
	}
	
	@Override
	public void onClick(View v) {
		int id = v.getId();
		if(id == R.id.btnSendMail)
		{
			String inviteCode= mInviteCode.getText().toString().trim();
			String email = mEmail.getText().toString().trim();
			
			if(inviteCode.length()<1){
				AdrewadsUtils.showMessage(getApplicationContext(), getString(R.string.login_invite_code_empty_warning));
				return;
			}
			if(email.length()<1){
				AdrewadsUtils.showMessage(getApplicationContext(), getString(R.string.login_invite_code_email_empty_warning));
				return;
			}
			buttonPressId=R.id.btnSendMail;
			if(isSending){
				return;
			}
			long mTime=System.currentTimeMillis();
			long time=(mTime-mCurrentTime)/1000;
			if(time > 3){
				mCurrentTime=mTime;
				sendMail();				
			}else{
				mCurrentTime=mTime;
				Toast.makeText(getApplicationContext(), getString(R.string.login_invite_code_warning), Toast.LENGTH_LONG).show();
			}
		}		
	}
	@Override
	protected void onResume() {
		super.onResume();
		getUserInfo();
		if(mInvitedData==null){
			loadInvitedData();
		}
	}
	@Override
	public void finish() {
		super.finish();
	}
	
	
	private void loadInvitedData(){
		if(mInvitedData==null){
			if(mLoadInvitedDataTask==null || mLoadInvitedDataTask.getStatus()==Status.FINISHED){
				mLoadInvitedDataTask=new LoadInvitedDataTask();
				mLoadInvitedDataTask.execute();
			}
		}
	}
	
	protected void showNotFoundOrLoadingView(boolean isShowNotFound,boolean isShowLoading){
		if(isShowNotFound){
			mNotFoundData.setVisibility(View.VISIBLE);
		}else{
			mNotFoundData.setVisibility(View.GONE);
		}
		if(isShowLoading){
			mWaitingForLoading.setVisibility(View.VISIBLE);
		}else{
			mWaitingForLoading.setVisibility(View.GONE);
		}
	}
	
	private void showMainView(boolean isShow){
		mMainView.setVisibility(isShow?View.VISIBLE:View.GONE);
	}
	
	
	private class LoadInvitedDataTask extends AsyncTask<Void, Void, InvitedFriendDTO>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();	
			showNotFoundOrLoadingView(false, true);
			showMainView(false);
		}
		@Override
		protected InvitedFriendDTO doInBackground(Void... params) {
			try {
				return CommonModel.getInstance().getInvitedFriendInfo();
			} catch (Exception e) {
 				return null;
			}			
		}
		@Override
		protected void onPostExecute(InvitedFriendDTO result) {
			super.onPostExecute(result);
			try {
				if(result!=null){
					mInvitedData=result;
					
					mMessage.setText(Html.fromHtml(mInvitedData.msg));
					mInviteNote.setText(Html.fromHtml(mInvitedData.note));
					//String mailDomains = mInviteData.mailDomain;
//					if(!TextUtils.isEmpty(mailDomains))
//					{
//						String[] domains = mailDomains.split(",");
//						List<String> list = new ArrayList<String>();
//						for (String item : domains) {
//						    list.add(item);
//						}
//						
//					}
					
					mDomains = mInvitedData.mailDomain;
					loadDomain();
					
					showNotFoundOrLoadingView(false,false);
					showMainView(true);
				}else{
					showNotFoundOrLoadingView(true, false);
					showMainView(false);
				}
			} catch (Exception e) {
				showNotFoundOrLoadingView(true, false);
				showMainView(false);
			}
		}
	}
	
	private void loadDomain()
	{
		ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, mDomains);
 
        // Drop down layout style - list view with radio button
        spinnerAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 
        // attaching data adapter to spinner
        mMailDomain.setAdapter(spinnerAdapter);
	}
	
	
	private void sendMail(){
		if(mSendMail==null || mSendMail.getStatus()==Status.FINISHED){
			mSendMail =new SendMailInviteCodeDataTask();
			mSendMail.execute();
		}
	}
	
	private class SendMailInviteCodeDataTask extends AsyncTask<Void, Void, ResultDTO>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			isSending=true;
			mProgressBar.setVisibility(View.VISIBLE);
		}
		@Override
		protected ResultDTO doInBackground(Void... params) {
			try {				
				String inviteCode= mInviteCode.getText().toString().trim();
				String email =  mEmail.getText().toString().trim() + String.valueOf(mMailDomain.getSelectedItem());
				
				return CommonModel.getInstance().sendMailInvite(inviteCode, email);
				
			} catch (Exception e) {
				return null;
			}			
		}
		@Override
		protected void onPostExecute(ResultDTO result) {
			super.onPostExecute(result);
			try {
				if(result!=null){
					
					if(buttonPressId==R.id.btnSendMail){
						if(!"0".equals(result.getError_code())){
							AdrewadsUtils.showMessage(getApplicationContext(), result.getError_message());
							return;
						}else{
							if(result.getSuccessMessage()!=null && result.getSuccessMessage().trim().length()>0){
								SuccessDialog mDialog=new SuccessDialog(LoginInviteCodeSendMailActivity.this, getString(R.string.sendmailcompleted), result.getSuccessMessage(), "home");
								mDialog.show();
							}else { 
								go2HomePage();
							}
						}
					}else{
						go2HomePage();
					}
				}else{
					AdrewadsUtils.showInfoDialog(getApplicationContext(), getString(R.string.error_message_title), getString(R.string.server_error_message));
				}
			} catch (Exception e) {
				AdrewadsUtils.showInfoDialog(getApplicationContext(), getString(R.string.error_message_title), getString(R.string.server_error_message));
			}
			finally{
				mProgressBar.setVisibility(View.INVISIBLE);
				isSending=false;
			}
		}
	}
	public void go2HomePage(){
		try {
			Intent intent=new Intent(getApplicationContext(), BaseNewActivity.class);
			intent.putExtra("m_id", "2835");
			intent.putExtra("m_owner_id", "558");
			if(mResult!=null && mResult.getMem_id()!=null && mResult.getMem_id().trim().length()>0){
				AppConfig.uId=mResult.getMem_id().trim();
				intent.putExtra("user_id", mResult.getMem_id().trim());
				intent.putExtra("uid", mResult.getMem_id().trim());
			}else{
				
				//intent.putExtra("user_id", "383cb3f413cc96b69cc78b818e433748");//account test
				//intent.putExtra("uid", "383cb3f413cc96b69cc78b818e433748");//account test
			}
			intent.putExtra("platform_id", "0");
			intent.putExtra("url", "http://car.mobadme.jp/spg/spnew/558/2835/index.php");
			intent.putExtra("api_key", "76552d4faa4dd35b");
			intent.putExtra("app_key", "ncIdX3la");
			intent.putExtra("loading_msg", "loading..");
			intent.putExtra("timeout", "3000");

			////
			
			intent.putExtra("appkey", "ncIdX3la");
			////

			intent.putExtra("show_button", true);
			intent.putExtra("button_string", "back");
			intent.putExtra("bk_color", Color.BLUE);
			intent.putExtra("button_gravity", Gravity.RIGHT);
			
			startActivity(intent);
			finish();
		} catch (Exception e) {
			return;
		}
	}
	@Override
	public void onStart() {
	    super.onStart();
	    try {
	    	EasyTracker.getInstance(this).activityStart(this);  // Add this method.
		} catch (Exception e) {			
		}
	  }

	  @Override
	  public void onStop() {
	    super.onStop();
	    try {
	    	EasyTracker.getInstance(this).activityStop(this);  // Add this method.
		} catch (Exception e) {
		}
	  }	 
}
